package com.lipuwater.agent.ui.activity.install;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lipuwater.agent.R;
import com.lipuwater.agent.app.base.ui.BaseLayoutActivity;
import com.lipuwater.agent.ble.eventbus.DeviceBindingEvent;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsBasis;
import com.lipuwater.agent.http.bean.install.InstallDesBean;
import com.lipuwater.agent.http.bean.user.RoleConfig;
import com.lipuwater.agent.ui.activity.PersonnelListActivity;
import com.lipuwater.agent.utils.MapToBeanUtil;
import com.lipuwater.agent.utils.onclick.NoDoubleClick;
import com.ismartlib.utils.NetUtils;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.Call;

import static com.lipuwater.agent.R.id.layout_order_allot;


public class InstallActivity extends BaseLayoutActivity {

    @Bind(R.id.text_state)
    TextView textState;
    @Bind(R.id.text_order_state)
    TextView textOrderState;
    @Bind(R.id.text_client_name)
    TextView textClientName;
    @Bind(R.id.text_mobile_phone)
    TextView textMobilePhone;
    @Bind(R.id.text_address)
    TextView textAddress;
    @Bind(R.id.text_courier_code)
    TextView textCourierCode;
    @Bind(R.id.text_way)
    TextView textWay;
    @Bind(R.id.text_install_name)
    TextView textInstallName;
    @Bind(R.id.text_install_state)
    TextView textInstallState;
    @Bind(R.id.layout_order_allot)
    LinearLayout layoutOrderAllot;


    private InstallDesBean mInstallDesBean;
    private int orderId;
    private int orderState;//工单状态 ，安装未安装
    private NoDoubleClick mNoDoubleClick = new NoDoubleClick();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyContentView(R.layout.activity_install);
        toolbar.setBackgroundResource(R.drawable.img_title_bar);
        initTitle(R.drawable.icon_aleft_white, "安装单详情");
        toolbarTitle.setTextColor(Color.parseColor("#ffffff"));
        ButterKnife.bind(this);
        showLoading();
        orderId = getIntent().getIntExtra("orderId", 0);
        getSalesDes();
        setReloadClickListener();
        EventBus.getDefault().register(this);
    }

    /**
     * 设备安装通知
     *
     * @param event
     */
    public void onEventMainThread(DeviceBindingEvent event) {
        if (event.getBinding()) {
            getSalesDes();
        }
    }

    @OnClick({R.id.layout_order_des, R.id.layout_settle_des, R.id.layout_order_allot})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_order_des:
                if (mNoDoubleClick.check()) return;
                if (mInstallDesBean != null) {
                    Intent intent = new Intent(this, InstallDeviceActivity.class);
                    intent.putExtra("deviceList", mInstallDesBean.getDeviceInfo());
                    intent.putExtra("orderState", mInstallDesBean.getOrderState());
                    startActivity(intent);
                } else {
                    Toast("没有设备信息");
                }
                break;
            case R.id.layout_settle_des:
                if (mNoDoubleClick.check()) return;
                if (mInstallDesBean != null) {
                    Intent intent = new Intent(this, InstallSettleListActivity.class);
                    intent.putExtra("SettlementList", mInstallDesBean.getSettlementInfo());
                    startActivity(intent);
                } else {
                    Toast("没有订单信息");
                }
                break;
            case layout_order_allot:
                if (mInstallDesBean.getState() == 1) {
                    Toast("工单已完成");
                    return;//已经完成
                }
                Intent intent = new Intent(this, PersonnelListActivity.class);
                intent.putExtra("choose", true);
                intent.putExtra("chooseType", "install");
                startActivityForResult(intent, 1);
                break;
        }
    }

    private void getSalesDes() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("orderId", orderId);
        ApiRequestsBasis.getInstallDes(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    mInstallDesBean = (InstallDesBean) MapToBeanUtil.toJavaBean(result.getParams().get("salesInfo"), InstallDesBean.class);
                    setData(mInstallDesBean);
                } else {
                    showNoNetWork();
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                showNoNetWork();
                if (NetUtils.isConnected(InstallActivity.this)) {
                    Toast(getString(R.string.service_error));
                } else {
                    Toast(getString(R.string.network_fails));
                }
            }
        });
    }

    private void setData(InstallDesBean installDes) {
        if (installDes != null) {
            orderId = installDes.getId();
            textState.setText(installDes.getStateString());
            textOrderState.setText(installDes.getOrderStateString());
            textClientName.setText(installDes.getClientName());
            textMobilePhone.setText(installDes.getMobilePhone());
            textAddress.setText(installDes.getInstallAddress());
            textCourierCode.setText(installDes.getCourierCode());
            textWay.setText(installDes.getDeliveryWay());
            if (installDes.getDeviceInfo() != null && installDes.getDeviceInfo().size() > 0 && installDes.getDeviceInfo().get(0) != null) {
                textInstallState.setText(installDes.getDeviceInfo().get(0).getState());
            }
            if (roleType.equals(RoleConfig.MANAGER)) {
                layoutOrderAllot.setVisibility(View.VISIBLE);
                if (installDes.getFulfiledBy() != null) {
                    textInstallName.setText(installDes.getFulfiledBy());
                } else {
                    textInstallName.setText(userName);
                }
            }
            hideEmptyLayout();
        } else {
            showNoNetWork();
        }
    }

    private void setReloadClickListener() {
        emptyLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLoading();
                getSalesDes();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case 101:
                    try {
                        String[] dataArray = data.getStringArrayExtra("data");
                        textInstallName.setText(dataArray[1]);
                        allotInstall(String.valueOf(orderId), dataArray[0]);
                    } catch (Exception e) {
                    }
                    break;
            }
        }
    }

    /**
     * 分配安装工单
     */
    private void allotInstall(String installId, String userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", token);
        params.put("workOrderId", installId);
        params.put("fulfiledBy", userId);
        ApiRequestsBasis.allotInstall(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    Toast("分配成功");
                } else {
                    Toast(result.getMessage());
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                if (NetUtils.isConnected(InstallActivity.this)) {
                    Toast(getString(R.string.service_error));
                } else {
                    Toast(getString(R.string.network_fails));
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }


}
